
//服务端接口路径
var server = Config.upurl + "/api/v2/sbxj/upload";
var AppId = mui.baseApp.AppId; //APPid
var AppKey = mui.baseApp.AppKey; // AppKey
var AppSecret = mui.baseApp.AppSecret; // AppSecret
var Version; // 版本
var timestamp = Date.parse(new Date()); // 时间戳
var OSType; // 系统
var DGUID;

//	拍照上传
$(".mui-card .img-up").on("tap", ".img", function() {
	var $img = $(this).parents().parents().parents('div');
	$img.addClass("selectLi");
	$img.siblings().removeClass("selectLi");
	page.imgUp();
})
//删除图片
$(".mui-card").on("tap", ".delete", function() {
	var H1 = $(this).parent();
	var img_btn = $(this).parents().children('.img');
	var img_s = $(this).siblings('img');
	var img_id = $(this).parents('.photo');
	var btnArray = ['否', '是'];
	mui.confirm('确定删除吗', '提示', btnArray, function(e) {
		if(e.index == 1) {
			H1.hide();
			img_btn.show();
			img_s.attr('src', "");
			img_id.attr('id', "");
		} else {}
	})
})

//弹出系统按钮选择框
var page = null;
page = {
	imgUp: function() {
		var m = this;
		console.log(m);
		plus.nativeUI.actionSheet({
			cancel: "取消",
			buttons: [{
					title: "拍照"
				},
				{
					title: "从相册中选择"
				}
			]
		}, function(e) { //1 是拍照  2 从相册中选择 
			switch(e.index) {
				case 1:
					appendByCamera();
					console.log("paizhao...")
					break;
				case 2:
					appendByGallery();
					break;
			}
		});
	}
}
// 拍照添加文件
function appendByCamera() {
	var cmr = plus.camera.getCamera();
	cmr.captureImage(function(e) {
		console.log("e is" + e);
		plus.gallery.save(e, function() {
			plus.io.resolveLocalFileSystemURL(e, function(entry) {
				var path = entry.toLocalURL();
				compressImage(path)
			}, function(e) {
				mui.toast("上传错误：" + e.message);
			})
		})
	}, function(e) {
		//					mui.toast("读取拍照文件错误：" + e.message+e.code);

		mui.toast("读取拍照文件错误：请先开启相机权限");
	});
}
Version = localStorage.getItem('version'); // 版本
console.log('version'+Version);
OSType = (mui.os.ios) ? "ios" : "android"; // 系统
if(localStorage.getItem("uuid") == null || localStorage.getItem("uuid") == "") {
	DGUID = plus.device.uuid;
	localStorage.setItem("uuid", param.DGUID);
} else {
	DGUID = localStorage.getItem("uuid");
}

// 从相册添加文件
function appendByGallery() {
	plus.gallery.pick(function(path) {
		compressImage(path);
	});
}
// 上传文件
function upload(path) {
	path = path.replace('file:','');
	console.log('server====='+server);
	var wt = plus.nativeUI.showWaiting();
	if (plus.networkinfo.getCurrentType()  ==  plus.networkinfo.CONNECTION_NONE)  {
		var indexa = liIndex();
		$(".photo").eq(indexa).css('display', 'block');
		console.log(indexa);
		$(".headimg")[indexa].src = path;
		$(".photo").eq(indexa).attr('id', path);
		/*$(".img").eq(indexa).hide();*/
		$(".img").eq(indexa).css('display', 'none');
		console.log('无网状态下地址' + path);
		wt.close(); //关闭等待提示按钮
	} else {
		var task = plus.uploader.createUpload(server + "?AppId=" + AppId + "&AppKey=" + AppKey + "&AppSecret=" + AppSecret + "&version=" + Version + "&timestamp=" + timestamp + "&OSType=" + OSType + "&DGUID=" + DGUID, {
				method: "POST"
			},
			function(t, status) { //上传完成
				if(status == 200) {
					console.log("上传成功：" + t.responseText);
					if(JSON.parse(t.responseText).status == 200) {
						var date = JSON.parse(t.responseText);
						var issavePath = date.data.savePath;
						console.log(date);
						var indexa = liIndex();
						$(".photo").eq(indexa).show();
						console.log(indexa);
						/*$(".headimg")[indexa].src = Config.upurl + issavePath;*/
						$(".headimg")[indexa].src = path;
						$(".photo").eq(indexa).attr('id', issavePath);
						$(".img").eq(indexa).hide();

					} else if(JSON.parse(t.responseText).status == 400) {
						mui.toast(JSON.parse(t.responseText).message);
						wt.close();
						return;
					}

					wt.close(); //关闭等待提示按钮

				} else {
					console.log("上传失败：" + JSON.stringify(t));
					console.log("上传失败：" + status);
					wt.close(); //关闭等待提示按钮
					mui.toast("上传失败");
				}
			}
		);
		//			//添加其他参数
		//	task.setRequestHeader('ContentType', 'multipart/form-data');
		task.addData("file", path);
		task.addFile(path, {
			key: path
		});
		task.start();
	}
}
//  压缩图片
function compressImage(path) {
	var itool = {
		options: {
			multiple: false,
			resize: {
				height: 0,
				width: 0
			},
			isResize: false,
			isZoom: true, //默认通过native.js压缩
			zoomBox: 8000, //缩放宽高，默认1200px,横图缩放宽度，高度根据比例计算，同理竖图
			//zoomQuality: mui.os.ios?10:20, //压缩图片的质量
			zoomQuality: mui.os.ios ? 90 : 100, //压缩图片的质量
			width: mui.os.ios ? "100%" : "100%", //压缩图片的宽度
		}
	}
	var name = path.substr(path.lastIndexOf('/') + 1);
	var names = name.split(".");
	var ext = names[names.length - 1];
	//生成随机文件名
	var uuid = UUID.prototype.createUUID();
	var filename = uuid + "." + ext;
	plus.zip.compressImage({
		src: path,
		dst: '_doc/' + filename,
		overwrite: true,
		quality: itool.options.ZoomQuality,
		width: itool.options.width
	}, function(zip) {
		console.log("图片压缩后地址" + zip.target);
		//压缩图片后开始上传 
		upload(zip.target, uuid);
	}, function(zipe) {
		//图片压缩失败
		//mui.toast("照片拍摄失败");
	});
}

function liIndex() {
	var lis = $(".xj-content").children('.mui-card');
	for(var i = 0; i < lis.length; i++) {
		var lisClass = $(lis[i]).attr("class").split(" ");
		if(lisClass[1] == "selectLi") {
			return i;
		}
	}
}